<template>
  <div>
    <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="100" class="form">
      <FormItem label="收件人" prop="receiverType">
        <RadioGroup v-model="formValidate.receiverType" vertical  @click="funUser2">
          <Row>
            <Col span="2">
            <Radio :label="formValidate.receiverTypeRadio.receiverType1">部分用户</Radio>
            </Col>
            <Col span="10" v-if="formValidate.receiverType== formValidate.receiverTypeRadio.receiverType1">
            <FormItem prop="messageReceivers">
              <Upload ref="uploadT"
                      :action="addressFile"
                      :before-upload="handleUploadFile"
                      :on-success="handleSuccess"
                      :format="uploadFormatFile"
                      :show-upload-list="showFileList"
                      :default-file-list="defaultList"
                      :on-format-error="handleFormatError">
                <Button type="ghost" icon="ios-cloud-upload-outline">上传用户文件</Button>
                <i v-if="isUploadOkFile">上传成功 &nbsp;&nbsp; &nbsp; <span style="color: red">{{formValidate.totalCount}}名用户上传成功！{{formValidate.repeatCount}}名重复，已去重。 </span>
                </i>
              </Upload>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="2">
            <span @click="fileClear"><Radio :label="formValidate.receiverTypeRadio.receiverType2" >全体用户</Radio></span>
            </Col>
          </Row>
        </RadioGroup>
      </FormItem>
      <FormItem label="接收渠道" prop="channel">
        <!--  <div style="padding-bottom:6px;margin-bottom:6px;">
            <checkbox
            :indeterminate="indeterminate"
            :value="checkAll"
            @click.prevent.native="handleCheckAll">全选</checkbox>
          </div>
          <checkbox-group v-model="formValidate.channel" @on-change="checkAllGroupChange">
            <checkbox  v-for='i in formValidate.channelArr' :label="i.val">{{i.label}}</checkbox>
          </checkbox-group>-->
        <RadioGroup v-model="formValidate.channel" vertical>
          <Row>
            <Col span="3">
            <Radio :label="1">Snap</Radio>
            </Col>
          </Row>
          <Row>
            <Col span="3">
            <Radio :label="2">element</Radio>
            </Col>
          </Row>
          <Row>
            <Col span="3">
            <Radio :label="3">life</Radio>
            </Col>
          </Row>
        </RadioGroup>
      </FormItem>

      <FormItem label="发送时间" prop="sendType">
        <RadioGroup v-model="formValidate.sendType" vertical>
          <Row>
            <Col span="3">
            <Radio :label="formValidate.sendTypeRadio.sendType1">立即发送</Radio>
            </Col>
          </Row>
          <Row>
            <Col span="3">
            <Radio :label="formValidate.sendTypeRadio.sendType2">定时发送</Radio>
            </Col>
            <div v-if="formValidate.sendType == formValidate.sendTypeRadio.sendType2 ">
              <Col span="6">
              <FormItem prop="sendTimeDate">
                <DatePicker type="datetime" :options="pickerSendTimeDate" format="yyyy-MM-dd HH:mm" placeholder="选择日期"
                            v-model="formValidate.sendTimeDate"></DatePicker>
              </FormItem>
              </Col>
            </div>
          </Row>
        </RadioGroup>
      </FormItem>

      <FormItem label="焦点信息" prop="isFocus">
        <RadioGroup v-model="formValidate.isFocus" vertical>
          <span @click="popupClear"><Radio label="0">否</Radio></span>
          <Radio label="1">是</Radio>
          <div class="subRadio">
            <Row>
              <div v-if="formValidate.isFocus== formValidate.isFocusRadio.isFocus1">
                <Row>
                  <Col span="2">
                  弹出图：</Col>
                  <Col span="10">
                  <FormItem prop="popupImage">
                    <Upload ref="uploadF"
                      :action="addressImg"
                      :format="uploadFormatImg"
                      :before-upload="handleUploadProp"
                      :on-success="handleSuccessProp"
                      :on-format-error="handleFormatError">
                      <Button type="ghost" icon="ios-cloud-upload-outline">上传弹出图</Button>
                      <i v-if="isUploadOkProp" span="6">上传成功</i>
                      <span style="color: red">&nbsp;&nbsp;支持PNG/JPG/GIF格式</span>
                    </Upload>
                  </FormItem>
                  </Col>
                  <Col span="2">
                  失效时间：</Col>
                  <Col span="8">
                  <!-- <FormItem prop="isFocusTime">
                     <DatePicker type="datetime" :model.sync="formValidate.invalidTime"  placeholder="选择日期和时间" style="width: 200px"></DatePicker>
                   </FormItem>-->
                  <FormItem prop="invalidTime">
                    <DatePicker type="datetime" :options="pickerInvalidTimeDate" format="yyyy-MM-dd HH:mm"  placeholder="选择日期"   v-model="formValidate.invalidTime"></DatePicker>
                  </FormItem>
                  </Col>
                </Row>

              </div>
            </Row>
          </div>
        </RadioGroup>
      </FormItem>

      <FormItem label="标题" prop="title">
        <Input v-model="formValidate.title" :maxlength="titleLen" @input="inputFont"></Input>
        <p><span>{{titleNum}}</span>/{{titleLen}}</p>
      </FormItem>

      <FormItem label="子标题" prop="subtitle">
        <Input v-model="formValidate.subtitle" maxlength="140" @input="inputFont"></Input>
        <p><span>{{subtitleNum}}</span>/140</p>
      </FormItem>

      <FormItem label="标题图">
        <Upload ref="uploadImg"
                :action="addressImg"
                :format="uploadFormatImg"
                :before-upload="handleUploadImg"
                :on-success="handleSuccessImg"
                :on-format-error="handleFormatError">
          <Button type="ghost" icon="ios-cloud-upload-outline">上传标题图</Button>
          <i v-if="isUploadOkImg" span="6">上传成功</i>
          <span  span="8" style="color: red">&nbsp;&nbsp;支持PNG/JPG/GIF格式</span>
        </Upload>
      </FormItem>

      <FormItem label="消息内容" prop="contentType">
        <RadioGroup v-model="formValidate.contentType" vertical>
          <Row>
            <Col span="3">
            <Radio label="1">文本内容</Radio>
            </Col>
            <div v-if="formValidate.contentType== formValidate.contentTypeRadio.contentType1">
              <Col span="21">
              <FormItem prop="content">
                <Input v-model="formValidate.content"
                       type="textarea"
                       :autosize="{minRows: 5,maxRows: 10}"
                       maxlength="255"
                       @input="descInput">
                </Input>
                <p><span>{{textNum}}</span>/{{textLen}}</p>
              </FormItem>
              </Col>
            </div>
          </Row>

          <Row>
            <Col span="3">
            <Radio label="2">跳转链接</Radio>
            </Col>
            <div v-if="formValidate.contentType== formValidate.contentTypeRadio.contentType2 ">
              <Col span="21">
              <FormItem prop="alink"><Input v-model="formValidate.alink"
                                            placeholder="示例: ?type=text 或者 ?type=coupon 或者 http://www.sengled.com/"></Input>
              </FormItem>
             <span @click="checkBoxChange"><Checkbox v-model="formValidate.targetBrowser" false-value="1" :true-value="2">跳转到手机外部浏览器打开</Checkbox></span>
              </Col>
            </div>
          </Row>
        </RadioGroup>
      </FormItem>

      <FormItem>
        <Button type="primary" :disabled="sendBtn" @click="handleSubmit('formValidate')">确定</Button>
        <Button type="ghost" @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
      </FormItem>
    </Form>

    <Modal v-model="modalMsg"
           title="消息需要审核后才能正式发送"
           :closable="false"
           :mask-closable="false"
            >
      <h3>测试人员列表</h3>
      <p v-for="item in testers">{{item}}</p>
      <div slot="footer">
        <Button type="info" size="large" @click="msgOk">确定</Button>
      </div>
    </Modal>

  </div>
</template>
<script>
  import * as validate from '../../lib/validate'
  import * as fuc from '../../lib/lib'
  import * as Url from '../../api/url'
  import axios from 'axios'
  import { MessageApi, Header } from '../../api/api'

  export default {
    data () {
      const validateIsFocusImg = (rule, value, callback) => {
        if(this.$refs.uploadF.fileList.length>0 || this.formValidate.popupImage !='' ){
          callback()
        }else {
          callback(new Error('请选择上传图片'))
        }
      };
      const validateIsFile = (rule, value, callback) => {
        if(this.$refs.uploadT.fileList.length>0 || this.formValidate.messageReceivers !=''){
          callback()
        }else {
          callback(new Error('请选择上传文件'))
        }
      }
      return {
        ID: this.$route.query.id,
        defaultList:[],
        showFileList:false,
        sendBtn: false,
        titleNum: 0,      //字限制从0开始--标题
        subtitleNum: 0,   //子标题
        textNum: 0,       //文本内容
        titleLen: 18,     //限制-->标题
        textLen: 255,     //限制-->文本
        addressImg: Url.root + '/message/uploadImage',//上传地址
        addressFile: Url.root + '/message/excel',//上传地址
        targetBrowserBool:true,
        targetBrowserVal:2,
        formValidate: {
          targetBrowser:1,
          isFocusTime: '',
          invalidTime: '',
          totalCount: '0',
          repeatCount: '0',
          receiverType: '',        //收件人        receiverType (integer): 全体用户接收： 2部分 1全部 ,
          receiverTypeRadio: {
            receiverType1: 2,        //部分用户2
            receiverType2: 1,        //全体用户1
          },
          messageReceivers: '', //excel名单,仅当收件人是局部的时候传值
          channel: '',      //渠道
          channelVal: '',   //渠道传值
          channelArr: [
            {label: 'Snap', val: 1},
            {label: 'element', val: 2},
            {label: 'life', val: 3},
          ],
          sendType: '',  //发送时间  sendType :1 立即发送 2 定时发送 ,
          sendTypeRadio: {
            sendType1: 1,  //立即发送
            sendType2: 2   //定时发送
          },
          sendTime: '', //定时---发送时间(yyyy-MM-dd HH:mm:ss)
          sendTimeDate: '',
          isFocus: '',   //焦点信息  0 否 1 是 ,
          isFocusRadio: {
            isFocus0: 0,
            isFocus1: 1
          },
          popupImage: '', //弹窗图 ,
          //invalidTime:'', //失效时间(yyyy-MM-dd HH:mm:ss) ,
          title: '', //标题
          subtitle: '',//子标题
          titleImage: '',//标题图

          contentType: '', // contentType (integer): 消息内容类型： 1文本内容 2跳转链接 ,
          contentTypeRadio: {
            contentType1: 1,   //文本内容
            contentType2: 2,   //跳转链接
          },
          content: '',//文本内容
          alink: ''//跳转链接内容
        },
        indeterminate: true,
        checkAll: false,
        channelSelect: true,
        requiredMesgRe: false,
        requiredSendTimeDate: false,
        requiredIsFocusImg: true,
        requiredIsFocusTime: false,
        requiredAlink: false,
        requiredContent: false,
        ruleValidate: {
          receiverType: [{required: true, message: '请选择收件人'}],
          messageReceivers: [{required: true, message: '请选择上传文件', trigger: 'change',validator:validateIsFile}],
          channel: [{required: true, message: '请选择接受渠道'}],
          sendType: [{required: true, message: '请选择发送时间'}],
          sendTimeDate: [{required: true, type: 'date', message: '请选择时间', trigger: 'change'}],
          isFocus: [{required: true, message: '请选择焦点信息'}],
          popupImage: [{required: true, message: '请选择上传图片', trigger: 'change',validator:validateIsFocusImg}],//validator:validateIsFocusImg
          isFocusTime: [{required: true, type: 'date', message: '请选择失效时间', trigger: 'change'}],
          invalidTime: [
            {required: true, type: 'date', message: '请选择失效时间', trigger: 'change'}
          ],
          title: [{required: true, message: '标题不能为空', trigger: 'blur'}],
          subtitle: [{required: true, message: '子标题不能为空', trigger: 'blur'}],
          titleImage: [{required: false, message: '标题图不能为空', trigger: 'blur'}],
          contentType: [{required: true, message: '请选择消息内容'}],
          alink: [{required: this.requiredAlink, message: '跳转链接内容不能为空', trigger: 'blur'}],
          content: [{required: this.requiredContent, message: '文本内容不能为空', trigger: 'blur'}]
        },
        modalMsg: false,
        isUploadOkFile: false,   //上传显示
        isUploadOkImg: false,   //上传显示
        isUploadOkProp: false,   //上传显示
        uploadFormatFile: ['xls', 'xlsx'],
        uploadFormatImg: ['png', 'jpg', 'gif'],
        uploadFile: [],  //文件
        uploadProp: [],  //弹框
        uploadImg: [],    //标题
        testers: [],//测试人员
        pickerInvalidTimeDate: {
          disabledDate: (date) => {
            return date && date.valueOf() <= Date.now() - 86400000;
          }
        },
        pickerSendTimeDate: {
          disabledDate (date) {
            return date && date.valueOf() <= Date.now() - 86400000;
          }
        }
      }
    },
    mounted: function () {
      this.$nextTick(function () {
        if (this.ID == '' || this.ID == 'undefined' || this.ID == null) {
          this.ID = 0
          //this.pageInit()
        } else {
          this.channelSelect = false
          this.pageFromXqing()
        }
      })
    },
    methods: {
      pageFromXqing(){
        axios.get(Url.message + this.ID).then(response => {
          //console.log(response.data.data);
          this.formValidate.targetBrowser = response.data.data.targetBrowser
          this.formValidate.receiverType = response.data.data.sendTarget
          this.formValidate.messageReceivers=response.data.data.messageReceivers;
          this.formValidate.channel = response.data.data.channel
          this.formValidate.sendType = response.data.data.sendType
          this.formValidate.sendTimeDate = response.data.data.sendTime
          this.formValidate.isFocus = response.data.data.isFocus
          this.formValidate.popupImage = response.data.data.popupImage
          this.formValidate.invalidTime = response.data.data.invalidTime
          this.formValidate.title = response.data.data.title
          this.formValidate.subtitle = response.data.data.subtitle
          this.formValidate.titleImage = response.data.data.titleImage
          this.formValidate.contentType = response.data.data.contentType
          this.formValidate.content = response.data.data.content
          this.formValidate.alink = response.data.data.alink
          if(this.formValidate.messageReceivers !=null){
            //this.uploadFile = this.formValidate.messageReceivers;
            this.isUploadOkFile =true;
            this.showFileList =true;
          }
          if(this.formValidate.popupImage !=null){
            //this.uploadProp = this.formValidate.popupImage;
          }
          if(this.formValidate.titleImage !=null){
            //this.uploadImg  = this.formValidate.titleImage;
          }

        }).catch(error => {
        })

      },
      inputFont(){
        this.titleNum = this.formValidate.title.length
        this.subtitleNum = this.formValidate.subtitle.length
        this.textNum = this.formValidate.content.length
      },
      descInput(){
        this.textNum = this.formValidate.content.length
      },
      titleInput(){
        this.titleNum = this.formValidate.title.length
      },
      handleCheckAll () {
        /* if (this.indeterminate) {
         this.checkAll = false;
         } else {
         this.checkAll = !this.checkAll;
         }
         this.indeterminate = false;

         if (this.checkAll) {
         this.formValidate.channel = [0,1,2,3];
         } else {
         this.formValidate.channel = [];
         }*/
      },
      checkAllGroupChange (data) {
        if (data.length === this.formValidate.channelArr.length + 1) {
          this.indeterminate = false
          this.checkAll = true
        } else if (data.length > 0) {
          this.indeterminate = true
          this.checkAll = false
        } else {
          this.indeterminate = false
          this.checkAll = false
        }
      },

      handleUploadFile(file){
        const count = this.uploadFile.length < 1
        if (!count) {
          this.$Message.error('只能上传一个文件')
        }
        return count
      },
      handleUploadProp(file){
        const count = this.uploadProp.length < 1
        if (!count) {
          this.$Message.error('只能上传一张图片')
        }
        return count
      },
      handleUploadImg(file){
        const count = this.uploadImg.length < 1
        if (!count) {
          this.$Message.error('只能上传一张图片')
        }
        return count
      },

      handleSuccess (res, file, fileList) {
        this.uploadFile = fileList
        this.showFileList =true;
            this.isUploadOkFile = true
            this.formValidate.messageReceivers = res.receivers
            this.formValidate.totalCount = res.totalCount
            this.formValidate.repeatCount = res.repeatCount
      },

      handleSuccessImg (res, file, fileList) {
        this.uploadImg = fileList
        this.isUploadOkImg = true
        this.formValidate.titleImage = res.downloadUrl
      },
      handleSuccessProp (res, file, fileList) {
          this.uploadProp = fileList
          this.isUploadOkProp = true
          this.formValidate.popupImage = res.downloadUrl
      },
      handleFormatError (file) {
        this.$Message.error(file.name + '格式不正确')
      },

      magModal(){
        this.modalMsg = true

      },
      msgOk(){
        this.$router.push({path: '/messageList'})
        this.handleReset('formValidate')
      },
      msgCancel(){
        this.sendBtn = false
        this.modalMsg = false
        //this.handleReset('formValidate');
      },

      handleSubmit (name) {
        this.formValidate.receiverType == 1 ? this.requiredMesgRe = true : this.requiredMesgRe = false
        this.formValidate.sendType == 2 ? this.requiredSendTimeDate = true : this.requiredSendTimeDate = false
        //this.formValidate.isFocus==1? this.requiredIsFocusImg=false:this.requiredIsFocusImg=true;
        //this.formValidate.isFocus==1? this.requiredIsFocusTime=true:this.requiredIsFocusTime=false;
        this.formValidate.contentType == 1 ? this.requiredContent = true : this.requiredContent = false
        this.formValidate.contentType == 2 ? this.requiredAlink = true : this.requiredAlink = false
        this.$refs[name].validate(valid => {
          //console.log(valid)
          if (valid) {
            this.sendBtn = !this.sendBtn
            if (this.ID == 0) {
              this.addMessage()
            } else {
              this.editMessage()
            }
          } else {
            //this.$Message.error('验证失败！');
          }

        })
      },
      checkBoxChange(){
        if(this.formValidate.targetBrowser==1){
          this.formValidate.targetBrowser=2;
        }else {
          this.formValidate.targetBrowser=1;
        }
      },
      handleReset (name) {
        this.$refs[name].resetFields()
        this.formValidate.sendTypeRadio.sendType2 = '';
        this.isUploadOkFile = false;
        this.formValidate.targetBrowser =1;
        /* this.$refs.uploadFile.fileList.splice(1,1);
         this.$refs.uploadProp.fileList.splice(1,1);
         this.$refs.uploadImg.fileList.splice(1,1);
         this.formValidate.receiverType='';
         this.formValidate.messageReceivers='';
         this.formValidate.channel='';
         this.formValidate.sendType='';
         this.formValidate.sendTime='';
         this.formValidate.isFocus='';
         this.formValidate.invalidTime='';
         this.formValidate.popupImage='';
         this.formValidate.title='';
         this.formValidate.subtitle='';
         this.formValidate.titleImage='';
         this.formValidate.contentType='';
         this.formValidate.content='';
         this.formValidate.alink='';*/

      },
      addMessage(){
        //this.formValidate.channelVal= this.formValidate.channel.toString();
        let data = {
          id: 0,
          sendTarget: this.formValidate.receiverType,      //接收人
          messageReceivers: this.formValidate.messageReceivers,      //接收人
          channel: this.formValidate.channel,     //渠道 格式"1,2,3,..."
          sendType: this.formValidate.sendType,    //发送类型
          sendTime: this.formValidate.sendType == 1 ? null : this.formValidate.sendTimeDate != '' ? fuc.dateFormatYMDHD(this.formValidate.sendTimeDate) : null,    //定时--发送时间
          isFocus: this.formValidate.isFocus, //
          popupImage: this.formValidate.popupImage, //弹框图
          invalidTime: this.formValidate.isFocus == 0 ? null : this.formValidate.invalidTime != '' ? fuc.dateFormatYMDHD(this.formValidate.invalidTime) : null, //失效时间
          title: this.formValidate.title,      //标题
          subtitle: this.formValidate.subtitle,  //子标题
          titleImage: this.formValidate.titleImage,   //标题图
          contentType: this.formValidate.contentType,   //文本内容
          content: this.formValidate.content,   //文本内容
          alink: this.formValidate.alink,   //跳转链接
          targetBrowser:this.formValidate.targetBrowser
        }
        //console.log(data);
        MessageApi.postMessage(data, {header: Header}).then(response => {
          if (response.messageCode == 200) {
            this.magModal()
            this.sendBtn = !this.sendBtn
            this.testers = response.data
            // this.$router.push({path: '/messageList'})
            this.handleReset()
          } else {
            this.$Message.error('发消息操作失败！')
            this.sendBtn = false
          }
        }).catch(error => {
          this.sendBtn = false
        })
      },
      popupClear(){
        this.uploadProp = []
        this.isUploadOkProp = false
      },
      fileClear(){
        this.isUploadOkFile = false
        this.uploadFile = []
      },
      editMessage(){
        //this.formValidate.channelVal= this.formValidate.channel.toString();
        let data = {
          id: this.ID,
          sendTarget: this.formValidate.receiverType,      //接收人
          messageReceivers: this.formValidate.messageReceivers,      //接收人
          channel: this.formValidate.channel,     //渠道 格式"0,1,2,3,..."
          sendType: this.formValidate.sendType,    //发送类型
          sendTime: this.formValidate.sendType == 1 ? null : this.formValidate.sendTimeDate != '' ? fuc.dateFormatYMDHD(this.formValidate.sendTimeDate) : null,    //定时--发送时间
          isFocus: this.formValidate.isFocus, //
          popupImage: this.formValidate.popupImage, //弹框图
          invalidTime: this.formValidate.isFocus == 0 ? null : this.formValidate.invalidTime != '' ? fuc.dateFormatYMDHD(this.formValidate.invalidTime) : null, //失效时间
          title: this.formValidate.title,      //标题
          subtitle: this.formValidate.subtitle,  //子标题
          titleImage: this.formValidate.titleImage,   //标题图
          contentType: this.formValidate.contentType,   //文本内容
          content: this.formValidate.content,   //文本内容
          alink: this.formValidate.alink,   //跳转链接
          targetBrowser:this.formValidate.targetBrowser
        }

        axios.put(Url.message + this.ID, data).then(response => {
          if (response.data.messageCode == 200) {
            this.magModal()
            this.sendBtn = !this.sendBtn
            this.testers = response.data.data
            //this.$router.push({path: '/messageList'})
            this.handleReset()
          } else {
            this.sendBtn = false
            this.$Message.error('编辑消息操作失败！')
          }
        }).catch(error => {
          this.sendBtn = false
        })
      }
    }
  }
</script>

<style scoped>
  .ivu-radio-group {
    display: block;
    font-size: 12px;
    vertical-align: middle;
  }

  .ivu-form .ivu-form-item-label {
    text-align: right;
    vertical-align: middle;
    float: left;
    font-size: 14px;
    color: #495060;
    line-height: 1;
    padding: 10px 12px 10px 0;
    box-sizing: border-box;
  }

  .form {
    margin-top: 20px;
    margin-right: 20px;
  }

  .subRadio {
    padding-left: 20px;
    margin-bottom: 20px;
  }
</style>
